$('#course').live("pagebeforeshow", function(event) {
	$('#info_tab').click();
	setTweetPage(0);
	localStorage["contact"] = null;
	createCoursePage();
});


/* creates the markup for the course page 	*
 * Needs a JSON object of the course		*/
function createCoursePage() {
	
	var course = getCurrentCourse();
	var moreQuestions = getMoreQuestionsBoolean();
		
	fillCourse();
		
	function getCurrentCourse() {
		var course = JSON.parse(localStorage["course"]);
		return course;
	}
	
	function getMoreQuestionsBoolean() {
		var mQuestions = JSON.parse(localStorage["moreQuestions"]);
		return mQuestions;
	}
	
	function fillCourse() {
		fillCourseInfo();
		var studentList = $('#course_students_list');
		fillCourseStudents(studentList);
	}
	
	function fillCourseInfo() {
		var questionList = $('#question_list');
		var tweetList = $('#tweet_list');
		
		fillCourseInfoInfo();
		fillCourseInfoQuestions(questionList);
		fillBasicTweetInfo(tweetList);
		fetchTweets(getTweetPage());
		
		questionList.listview("refresh");
		tweetList.listview("refresh");
	}
	
	function fillCourseInfoInfo() {
		$('#course_title').empty();
		$('#staff').empty();
		$('#course_title').append(course.name)
		localStorage["contact"] = JSON.stringify(course.prof);
		$('#staff').append('<li data-role="list-divider">Staf</li>');
		$('#staff').append('<li><a href="#contact">Professor: '+course.prof.name+'</a></li>');
		$('#staff').listview("refresh");
	}
	
	function fillBasicQuestionInfo(courseInfo) {
		$('#question_list').empty();
		
		var div = $('<li data-role="list-divider">Vragen</li>');
		courseInfo.append(div);
		
		nv = $('<li data-theme="e"><a href="#" class="view" data-rel="dialog">+ Stel een nieuwe vraag...</a></li>');
		nv.find('a').click(newQuestion);
		courseInfo.append(nv);
	}
	
	function fillCourseInfoQuestions(courseInfo) {
		fillBasicQuestionInfo(courseInfo);
		
		$.ajax( {
			url: "/api/vraag/"+course.vakId,
			dataType:"json",
			success: function(data) {
				fillBasicQuestionInfo(courseInfo);
				var questions = data.result;
				if(questions.length > 0){
					if(questions.length < 2) {
						var n = questions.length;
					} else if(moreQuestions.bool=="false"){
						var n = 2;
					} else {
						var n = questions.length;
					}
					for( var i=0;i<n;i++) {
						li = $('<li><a href="#" class="view" data-rel="dialog">'+questions[i].subject+'</a></li>'); //DIALOG NEEMT IDE NOG NIE TOEGOEI, WEET NIET JUIST HOE DIT KOMT
						li.find('a').jqmData('screenName',questions[i]).click(viewQuestion);
						courseInfo.append(li);
					}
					if(questions.length > 2) {
						if(moreQuestions.bool=="false"){
							li = $('<li data-theme="e"><a href="#">+ Toon alle vragen...</a></li>');
						} else {
							li = $('<li data-theme="e"><a href="#">- Verberg vragen...</a></li>');
						}
						li.find('a').click(toggleMoreQuestions);
						courseInfo.append(li);
					}
				}
				courseInfo.listview("refresh");
			},
			error: function() {
				console.log("** ERROR: Can not load json object **");
			}
		});
	}	
	
	function viewQuestion(){
		question = $(this).jqmData('screenName');		// get the course
		
		localStorage.removeItem("question");
		localStorage["question"] = JSON.stringify(question);
		
		$.mobile.changePage('#question');		// load the page
	}
	
	function newQuestion(){
		$.mobile.changePage('#new_question');		// load the page
	}

	function fillCourseStudents(studentList){
		$.ajax( { 
			url: "/api/vak/user/"+course.vakId,
			dataType:"json",
			success: function(data) {
				studentList.empty();
				var students = data.result;
				for(var i=0; i<students.length; i++) {
					li = $('<li><a href="#" class="view"  data-rel="dialog" data-transition="pop">'+students[i].username+'</a></li>');
					li.find('a').jqmData('person',students[i]).click(contact);
					studentList.append(li);
				}
				studentList.listview("refresh");
			},
			error: function() {
				console.log("** ERROR: Can not load json object **");
			}
		});
	}
}

function fillBasicTweetInfo(courseInfo) {
	$('#tweet_list').empty();
	var li = $('<li data-role="list-divider">Tweets</li>');
	courseInfo.append(li);
	
	li = $('<li data-theme="e"><a href="#make_tweet" data-rel="dialog" data-transition="pop">+ Nieuwe tweet...</a></li>');
	courseInfo.append(li);
}

function showMoreTweets() {
	if(localStorage.moreTweets == "true") {
		setTweetPage(getTweetPage() + 1);
		fetchTweets(getTweetPage());
	}else{
		localStorage.moreTweets = "true";
		$('#tweet_list').empty();
		fillBasicTweetInfo($('#tweet_list'));
		fetchTweets(getTweetPage());
	}
}

function hideTweets() {
	localStorage.moreTweets = "false";
	setTweetPage(0);
	$('#tweet_list').empty();
	fillBasicTweetInfo($('#tweet_list'));
	fetchTweets(getTweetPage());
}

function fetchTweets(page) {
	courseInfo = $('#tweet_list');
	course = JSON.parse(localStorage["course"]);
	
	$.ajax( { 
		url: "/api/tweet?hashtag="+course.hashTag+"&rpp=10&page="+page,
		dataType:"json",
		success: function(data) {
			var tweets = data.result;
			if(tweets.length > 0){
				if(tweets.length < 2) {
					var n = tweets.length;
				} else if(localStorage.moreTweets=="false"){
					var n = 2;
				} else {
					var n = tweets.length;
				}
				for( var i=0;i<n;i++) {
					date = tweets[i].datestamp.substring(0,17);
					li = $('<li><img src='+tweets[i].image+' /><p><strong>'+tweets[i].author+'</strong></p><p style="white-space:normal">'+tweets[i].text+'</p><p>'+date+'</p></li>');
					courseInfo.append(li);
				}			
			}
			courseInfo.listview("refresh");
		},
		error: function() {
			console.log("** ERROR: Can not load json object **");
		}
	});
}

function getTweetPage() {
	return parseInt(localStorage.tweetPage);
}

function setTweetPage(n) {
	localStorage.tweetPage = n;
}

function toggleMoreQuestions(){
	var moreQuestions = JSON.parse(localStorage["moreQuestions"]);
	
	localStorage.removeItem("moreQuestions");
	if(moreQuestions.bool == "true") {
		var moreQuestions = {"bool":"false"};
	}else{
		var moreQuestions = {"bool":"true"};
	}
	
	localStorage["moreQuestions"] = JSON.stringify(moreQuestions);
	createCoursePage();
}

function contact() {
	person = $(this).jqmData('person');
	localStorage["contact"] = JSON.stringify(person);
	$.mobile.changePage('#contact');
}